package com.example.demo.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.tools.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

import com.example.demo.controller.Result;
import com.example.demo.sys.mapper.ForumMapper;
import com.example.demo.sys.entity.Forum;

import org.springframework.web.bind.annotation.RestController;
import com.example.demo.common.tools.BaseController;

/**
 * <p>
    *  前端控制器 chrimer
    * </p>
 *
 * @author chrimer
 * @since 2020-06-28z
 */
@RestController
@RequestMapping("/sys/forum")
public class ForumController extends BaseController {
    @Autowired
    private ForumMapper forumMapper;

    @RequestMapping(method= RequestMethod.POST,value="/page")
    public Result page(Integer pageNum, String title, String type, String key,String courseId) {
        Result result = new Result();
        int pageSize = 8;
        Page<Forum> page = new Page<Forum>(pageNum, pageSize);
        Forum parms = new Forum();
        QueryWrapper<Forum> warpper = new QueryWrapper<Forum>(parms);
        //key的 0代表按条件搜索，1代表直接选择板块
        System.out.println(courseId);
        if(key.equals("1")) warpper.nested(i-> i.eq("discussType",type).eq("courseId",courseId));
        else if(key.equals("0"))
        {
            if(type.equals("全部讨论区")) warpper.nested(i-> i.eq("courseId",courseId).like("discussTitle",title));
            else warpper.nested(i-> i.eq("discussType",type).like("discussTitle",title).eq("courseId",courseId));
        }
        warpper.orderByDesc("createTime");
        result.setData(forumMapper.selectPage(page, warpper));
        return result;
    }
    @RequestMapping(method= RequestMethod.POST,value="/save")
    public Result save(@RequestBody Forum entity) {
        Result result = new Result();
        if (entity.getId() == null) {//讨论区发帖
            entity.setCreateTime(DateTool.getCurrTime());
            entity.setAnswer(0);
            forumMapper.insert(entity);
        } else {
            forumMapper.updateById(entity);
        }
        return result;
    }
    @RequestMapping(method= RequestMethod.DELETE,value="/delete")
    public Result delete( String ids) {
        Result result = new Result();
        List<String> deleteIds = new ArrayList<String>();
        for (String id : ids.split(",")) {
            deleteIds.add(id);
        }
    forumMapper.deleteBatchIds(deleteIds);
        return result;
    }

}
